package com.twu.biblioteca;

import java.io.*;
import java.util.ArrayList;
import java.util.logging.Logger;


/**
 * Created with IntelliJ IDEA.
 * User: "Balasubramanian"
 * Date: 8/30/13
 * Time: 7:41 AM
 * To change this template use File | Settings | File Templates.
 */
public class Authenticator {

    private MemberController memberController;
    private Logger logger;

    final String ERROR_MESSAGE="Sorry,the system has encountered an error. Please try again later";


    Authenticator(MemberController memberController,Logger logger)
    {
        this.logger=logger;
        this.memberController=memberController;
    }

    String authenticate(BufferedReader reader)
    {
        String memberId=readMemberIdFromConsole(reader);
        String password=readPasswordFromConsole(reader);

        if(isInvalidMember(memberId))
            return null;
        if(passwordMatches(memberId,password))
            return memberId;
        else
        {
            return null;
        }
    }


    private boolean isInvalidMember(String memberId)
    {
        if(memberController.isValidMemberId(memberId))
            return false;
        return true;
    }

    private boolean passwordMatches(String memberId,String password)
    {
        Member member=memberController.getMemberDetails(memberId);
        if(member.getPassword().equals(password))
            return true;
        return false;
    }

    private String readMemberIdFromConsole(BufferedReader reader)
    {
        String userId="";
        System.out.print("Enter your user id:");
        try
        {
            userId=reader.readLine();
        }
        catch(IOException e)
        {
            System.out.println(ERROR_MESSAGE);
            logger.severe(e.toString());
            System.exit(1);
        }
        return userId;
    }

    private String  readPasswordFromConsole(BufferedReader reader)
    {
        String password="";
        System.out.print("Enter your password:");
        try
        {
            password=reader.readLine();
        }
        catch(IOException e)
        {
            System.out.println(ERROR_MESSAGE);
            logger.severe(e.toString());
            System.exit(1);
        }
        return password;
    }

}
